package com.langsheng.lsintell.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by xuwei on 2016/6/20.
 */
public class LSUtil {

    private static Toast toast;

    private static MessageDigest md5 = null;

    static {
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 创建一个新的guid
     *
     * @return
     */
    public static String newGuid() {
        return UUID.randomUUID().toString().toUpperCase(Locale.getDefault());
    }

//    public static String startTakePhoto(Activity context, int request) {
//        try {
//            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            File file = createCaptureFile();
//            Uri uri = Uri.fromFile(file);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//            context.startActivityForResult(intent, request);
//            return file.getAbsolutePath();
//        } catch (IOException e) {
//            e.printStackTrace();
//            return null;
//        }
//    }
//
//    public static File createCaptureFile() throws IOException {
//        String filePath = LSStaticPath.PIC_FOLDER;
//        String name = LSUtil.newGuid() + ".png";
//        File dir = new File(filePath);
//        dir.mkdirs();
//        File file = new File(filePath + name);
//        return file;
//    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
        try {
            String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            return matcher.matches();
        } catch (Exception e) {
            return false;
        }
    }

    public static int dp2px(Activity context, int dp) {
        DisplayMetrics metric = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(metric);
        return (int) (metric.density * dp);  // 屏幕密度（0.75 / 1.0 / 1.5）
    }

    public static void showToast(Context context, String text) {
        try {
            if (toast != null) {
                toast.cancel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        toast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_SHORT);
        toast.show();
    }

    public static void showError(Context context, String errCode) {
        int resID = LSR.getStringRes(context, "error_code_" + errCode);
        String err;
        if (resID == 0) {
            err = "未知错误";
        } else {
            err = context.getString(resID);
        }
        LSUtil.showToast(context, err);
    }

    public static void showToast(Context context, int resID) {
        try {
            if (toast != null) {
                toast.cancel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        toast = Toast.makeText(context.getApplicationContext(), resID, Toast.LENGTH_SHORT);
        toast.show();
    }

    public static Drawable getBoundedDrawable(Context context, int res) {
        Drawable draw = context.getResources().getDrawable(res);
        if (draw != null) {
            draw.setBounds(0, 0, draw.getMinimumWidth(), draw.getMinimumHeight());
        }
        return draw;
    }

    public static void closeInputMethod(Activity context) {
        try {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive()) {
                imm.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 打开文件
     *
     * @param file
     * @param context
     */
    public static void openFile(final File file, Context context) {

        Intent intent = new Intent();
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);

        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        context.startActivity(intent);
    }

    private static String getMIMEType(final File file) {
        String type = "";
        String name = file.getName();
        // 文件扩展名
        String end = name.substring(name.lastIndexOf('.') + 1, name.length());
        if (end.equalsIgnoreCase("m4a") || end.equalsIgnoreCase("mp3") || end.equalsIgnoreCase("wav")
                || end.equalsIgnoreCase("ogg") || end.equalsIgnoreCase("amr")) {
            type = "audio";
        } else if (end.equalsIgnoreCase("mp4") || end.equalsIgnoreCase("3gp")) {
            type = "video";
        } else if (end.equalsIgnoreCase("jpg") || end.equalsIgnoreCase("png") || end.equalsIgnoreCase("jpeg")
                || end.equalsIgnoreCase("bmp") || end.equalsIgnoreCase("gif")) {
            type = "image";
        } else if (end.equalsIgnoreCase("txt") || end.equalsIgnoreCase("java") || end.equalsIgnoreCase("log")
                || end.equalsIgnoreCase("c") || end.equalsIgnoreCase("cpp") || end.equalsIgnoreCase("xml")
                || end.equalsIgnoreCase("ini") || end.equalsIgnoreCase("bat")) {
            type = "text";
        } else {
            type = "*";
        }
        type += "/*";
        return type;
    }

    /**
     * 将文件大小转化为计数字符串
     *
     * @param fileSize
     * @return
     */
    public static String changFileSizeToString(long fileSize) {
        String size = "";
        if (fileSize > 1024 * 1024 * 1024) {
            size = new DecimalFormat("####.##").format((fileSize >>> 20) / 1024.0) + "GB";
        } else if (fileSize > 1024 * 1024) {
            size = new DecimalFormat("####.##").format((fileSize >>> 10) / 1024.0) + "MB";
        } else if (fileSize > 1024) {
            size = new DecimalFormat("####.##").format(((fileSize)) / 1024.0) + "KB";
        } else {
            size = fileSize + "B";
        }
        return size;
    }

    /**
     * 将文件大小转化为计数字符串
     *
     * @param strSize
     * @return
     */
    public static String changFileSizeToString(String strSize) {
        long fileSize = 0;
        try {
            fileSize = Long.valueOf(strSize);
        } catch (NumberFormatException e) {
        }
        return changFileSizeToString(fileSize);
    }

    /**
     * 获取录音长度,单位秒s
     *
     * @param path
     * @return
     */
    public static int getRecordFileDuration(String path) {
        if (TextUtils.isEmpty(path)) {
            return 0;
        }
        try {
            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            float length = (float) mediaPlayer.getDuration() / (float) 1000;
            if (length > 0 && length < 1) {
                return 1;
            } else {
                return (int) (length + 0.5);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

//    /**
//     * 从资源中获取错误提示
//     *
//     * @param context
//     * @param errCode
//     * @return
//     */
//    public static String getErrorInfo(Context context, int errCode) {
//        int id = LSR.getStringRes(context, "error_code_" + errCode);
//        if (id == 0) {
//            return "unknown error " + errCode;
//        }
//        return context.getResources().getString(id);
//    }
//
//    public static char[] getChars(byte[] bytes) {
//        Charset cs = Charset.forName(BAStringTable.CHARSET_UTF8);
//        ByteBuffer bb = ByteBuffer.allocate(bytes.length);
//        bb.put(bytes);
//        bb.flip();
//        CharBuffer cb = cs.decode(bb);
//        return cb.array();
//    }

    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

    public static boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (char c : ch) {
            return isChinese(c);
        }
        return false;
    }

    /**
     * 跳转到拨打电话界面
     *
     * @param tv
     * @param phone
     */
    public static void callPhone(TextView tv, final String phone, final Context context) {
        if (phone == null) {
            tv.setText("");
            return;
        } else if (phone.trim().isEmpty()) {
            tv.setText("");
            return;
        }
        SpannableString span = new SpannableString(phone);
        span.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));//跳转到拨号界面，同时传递电话号码
                context.startActivity(dialIntent);
            }
        }, 0, phone.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setText(span, TextView.BufferType.SPANNABLE);
    }

    /**
     * 用于获取一个String的md5值
     *
     * @param str
     * @return
     */
    public static String getMd5(String str) {
        byte[] bs = md5.digest(str.getBytes());
        StringBuilder sb = new StringBuilder(40);
        for (byte x : bs) {
            if ((x & 0xff) >> 4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString();
    }

}
